import axios from 'axios'
import { ElMessage } from 'element-plus'

const api = axios.create({
  baseURL: '/api',
  timeout: 120000,  // 设置更长的超时时间
  retry: 3,         // 重试次数
  retryDelay: 1000  // 重试间隔
})

// 添加请求重试拦截器
api.interceptors.response.use(null, async error => {
  const config = error.config;
  
  // 如果配置不存在或重试次数用完，则拒绝请求
  if (!config || !config.retry) {
    return Promise.reject(error);
  }
  
  // 设置用于跟踪重试计数的变量
  config.__retryCount = config.__retryCount || 0;
  
  // 如果已经达到最大重试次数，则拒绝请求
  if (config.__retryCount >= config.retry) {
    return Promise.reject(error);
  }
  
  // 增加重试计数
  config.__retryCount += 1;
  console.log(`正在进行第 ${config.__retryCount} 次重试`);
  
  // 创建新的 Promise 用于延迟重试
  const backoff = new Promise(resolve => {
    setTimeout(() => {
      resolve();
    }, config.retryDelay || 1000);
  });
  
  // 等待延迟时间后重试请求
  await backoff;
  return api(config);
});

// 添加响应拦截器，统一处理错误
api.interceptors.response.use(
  response => response,
  error => {
    console.error('API请求错误:', error.response || error)
    
    // 根据错误状态码显示不同的错误信息
    if (error.response) {
      const status = error.response.status
      
      if (status === 500) {
        ElMessage.error('服务器内部错误，请联系管理员')
      } else if (status === 404) {
        ElMessage.error('请求的资源不存在')
      } else if (status === 401) {
        ElMessage.error('未授权，请登录')
      } else if (status === 403) {
        ElMessage.error('没有权限执行此操作')
      } else {
        ElMessage.error(`请求失败: ${error.response.data?.message || '未知错误'}`)
      }
    } else if (error.request) {
      ElMessage.error('无法连接到服务器，请检查网络连接')
    } else {
      ElMessage.error('请求配置错误')
    }
    
    return Promise.reject(error)
  }
)

// 添加 WebSocket 配置
export const wsConfig = {
  publishEndpoint: `ws://${window.location.host}/ws/publish`
}

export const projectApi = {
  getAll: () => api.get('/projects'),
  getById: (id) => api.get(`/projects/${id}`),
  getByOwner: (owner) => {
    return api.get('/projects/search/owner', { params: { owner } })
  },
  getByName: (name) => {
    return api.get('/projects/search/name', { params: { name } })
  },
  getByOwnerAndName: (owner, name) => {
    return api.get('/projects/search', { params: { owner, name } })
  },
  create: (project) => api.post('/projects', project),
  update: (id, project) => api.put(`/projects/${id}`, project),
  delete: (id) => api.delete(`/projects/${id}`),
  batchDelete: (ids) => api.delete('/projects/batch', { data: ids })
}

// 其他API保持不变
export const developerInfoApi = {
  getAll: () => api.get('/developer-info'),
  getById: (id) => api.get(`/developer-info/${id}`),
  // 按组织名称搜索
  getByOwner: (owner) => {
    return axios.get(`/api/developer-info/search/owner`, { params: { owner } })
  },

  // 按库名称搜索
  getByName: (name) => {
    return axios.get(`/api/developer-info/search/name`, { params: { name } })
  },

  // 组合搜索（已存在，保持不变）
  getByOwnerAndName: (owner, name) => {
    return axios.get(`/api/developer-info/search`, { params: { owner, name } })
  },
  create: (developerInfo) => api.post('/developer-info', developerInfo),
  update: (id, developerInfo) => api.put(`/developer-info/${id}`, developerInfo),
  delete: (id) => api.delete(`/developer-info/${id}`),
  batchDelete: (ids) => api.delete('/developer-info/batch', { data: ids }),
  toggleUpdate: () => api.post('/developer-info/toggle-update'),
  getUpdateStatus: () => api.get('/developer-info/update-status')
}

export const publishInfoApi = {
  getAll: () => api.get('/publish-info'),
  getById: (id) => api.get(`/publish-info/${id}`),
   // 按组织名称搜索
   getByOwner: (owner) => {
    return axios.get(`/api/publish-info/search/owner`, { params: { owner } })
  },

  // 按库名称搜索
  getByName: (name) => {
    return axios.get(`/api/publish-info/search/name`, { params: { name } })
  },
  // 组合搜索（已存在，保持不变）
  getByOwnerAndName: (owner, name) => {
    return axios.get(`/api/publish-info/search`, { params: { owner, name } })
  },
  create: (publishInfo) => api.post('/publish-info', publishInfo),
  update: (id, publishInfo) => api.put(`/publish-info/${id}`, publishInfo),
  delete: (id) => api.delete(`/publish-info/${id}`),
  toggleUpdate: () => api.post('/publish-info/toggle-update'),
  getUpdateStatus: () => api.get('/publish-info/update-status'),
  initPublish: (data) => api.post('/publish-info/init-publish', data),
  publish: (data) => api.post('/publish-info/publish', data),
  // 修改批量发布方法的实现
  batchPublish: (publishItems) => api.post('/publish-info/batch-publish', publishItems)
}

export const xtsReportApi = {
  getAll: () => api.get('/xts-reports'),
  getById: (id) => api.get(`/xts-reports/${id}`),
  getByOwnerAndName: (owner, name) => api.get(`/xts-reports/search?owner=${owner}&name=${name}`),
  create: (xtsReport) => api.post('/xts-reports', xtsReport),
  update: (id, xtsReport) => api.put(`/xts-reports/${id}`, xtsReport),
  delete: (id) => api.delete(`/xts-reports/${id}`)
}